﻿using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using HRMS.Models.ModelBinders;
using HRMS_Model;
using HRMS.Models;
using System.Web.UI;
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Lib.Web.Mvc.JQuery.JqGrid;


namespace HRMS.Controllers
{
    public class DepartmentController : Controller
    {
        //
        // GET: /Department/

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Departments(JqGridRequest request)
        {
            //get the count of employees
            var totalRecords = DepartmentsModel.GetDepartmentsCount();

            //Prepare JqGridData instance
            var response = new JqGridResponse
            {
                //Total pages count
                TotalPagesCount = (int)Math.Ceiling((float)totalRecords / (float)request.RecordsCount),
                //Page number
                PageIndex = request.PageIndex,
                //Total records count
                TotalRecordsCount = totalRecords
            };

            //Get employees
            var departments = DepartmentsModel.GetDepartments(request.SortingName.ToString(CultureInfo.InvariantCulture), request.SortingOrder.ToString(), request.PageIndex, request.RecordsCount, request.PagesCount.HasValue ? request.PagesCount.Value : 1);

            //Table with rows data
            foreach (var department in departments)
            {
                response.Records.Add(new JqGridRecord(Convert.ToString(department.DepartmentId),
                    new List<object> { 
                                    department.DepartmentId,
                 department.DepartmentName
                    }
                ));
            }

            //Return data as json
            return new JqGridJsonResult() { Data = response };
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult InsertDepartment(Department deptModel)
        {
            return Json(DepartmentsModel.AddDepartment(deptModel));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UpdateDepartment([ModelBinder(typeof(DepartmentModelBinder))]Department deptModel)
        {
            return Json(DepartmentsModel.UpdateDepartment(deptModel));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteDepartment(int id)
        {
            return Json(DepartmentsModel.DeleteDepartment(id));
        }

    }
}

         